package com.storage.joyce.storageapp.util;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by john on 2016/2/22.
 */
public class CommonJSONParser {
    /**
     * json转换成Map格式
     *
     * @param jsonStr json字符串String类型
     * @return Map<String,Object>  Object可以是String或List<Map<String, Object>>
     */
    public static Map<String, Object> parse(String jsonStr) {
        System.out.println(jsonStr);
        jsonStr = jsonStr.replace("\\", "^%^%174%^%^");
        System.out.println(jsonStr);

        Map<String, Object> result = null;

        if (null != jsonStr) {
            try {

                JSONObject jsonObject = new JSONObject(jsonStr);
                result = parseJSONObject(jsonObject);

            } catch (JSONException e) {
                Log.e("eee", "JsonToMap出错" + e);
                return null;
            }
        } // if (null != jsonStr)

        return result;
    }

    /**
     * Map转换成json格式
     *
     * @param map Map<String,Object>  Object可以是String或List<Map<String, Object>>
     * @return json字符串String类型
     */
    public static String MapToJson(Map<String, Object> map) {
        if (map == null || map.size() == 0) return null;
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            for (Map.Entry<String, Object> set : map.entrySet()) {
                if (null == set.getValue()) continue;
                if (set.getValue() instanceof Collection) {
                    Collection<Map<String, Object>> list = (Collection<Map<String, Object>>) set.getValue();
                    if (list.size() == 0) continue;
                    JSONArray jsonArray = new JSONArray();
                    for (Map<String, Object> data : list) {
                        if (null == data || data.size() == 0) continue;
                        JSONObject jsonObject1 = new JSONObject();
                        for (Map.Entry<String, Object> mapDataset : data.entrySet()) {
                            if (mapDataset.getValue() == null ||
                                    mapDataset.getValue().toString().length() == 0) continue;
                            jsonObject1.put(mapDataset.getKey(), StringDanYinToJSON(mapDataset.getValue().toString()));
                        }
                        jsonArray.put(jsonObject1);
                    }
                    jsonObject.put(set.getKey(), jsonArray);
                }else if (set.getValue() instanceof Map){
                    Map<String,Object> setMap= (Map<String, Object>) set.getValue();
                    JSONObject jsonObject2 = new JSONObject();
                    for (Map.Entry<String, Object> mapDataset :setMap.entrySet()) {
                        if (mapDataset.getValue() == null ||
                                mapDataset.getValue().toString().length() == 0) continue;
                        jsonObject2.put(mapDataset.getKey(), StringDanYinToJSON(mapDataset.getValue().toString()));
                    }
                    jsonObject.put(set.getKey(),jsonObject2);
                }else {
                    if (set.getValue().toString().length() == 0) continue;
                    jsonObject.put(set.getKey(), set.getValue().toString());
                }
            }
        } catch (Exception e) {
            Log.e("eee", "MapToJson出错" + e);
        }
        return jsonObject.toString();

    }

    private static Object parseValue(Object inputObject) throws JSONException {
        Object outputObject = null;

        if (null != inputObject) {

            if (inputObject instanceof JSONArray) {
                outputObject = parseJSONArray((JSONArray) inputObject);
            } else if (inputObject instanceof JSONObject) {
                outputObject = parseJSONObject((JSONObject) inputObject);
            } else if (inputObject instanceof Boolean
                    || inputObject instanceof Integer
                    || inputObject instanceof Float
                    || inputObject instanceof Double) {
                outputObject = inputObject;
            } else if (inputObject instanceof String) {
                outputObject = ((String) inputObject).replace("^%^%174%^%^", "\\");
            }

        }

        return outputObject;
    }

    private static Collection<Object> parseJSONArray(JSONArray jsonArray)
            throws JSONException {

        Collection<Object> valueList = null;

        if (null != jsonArray) {
            valueList = new ArrayList<Object>();

            for (int i = 0; i < jsonArray.length(); i++) {
                Object itemObject = jsonArray.get(i);
                if (null != itemObject) {
                    valueList.add(parseValue(itemObject));
                }
            } // for (int i = 0; i < jsonArray.length(); i++)
        } // if (null != valueStr)

        return valueList;
    }

    private static Map<String, Object> parseJSONObject(JSONObject jsonObject)
            throws JSONException {

        Map<String, Object> valueObject = null;
        if (null != jsonObject) {
            valueObject = new HashMap<String, Object>();

            Iterator<String> keyIter = jsonObject.keys();
            while (keyIter.hasNext()) {
                String keyStr = keyIter.next();
                Object itemObject = jsonObject.opt(keyStr);
                if (null != itemObject) {
                    valueObject.put(keyStr, parseValue(itemObject));
                } // if (null != itemValueStr)

            } // while (keyIter.hasNext())
        } // if (null != valueStr)

        return valueObject;
    }
    private static String StringDanYinToJSON(String ors) {
        ors= ors == null ? "" : ors;
        StringBuffer buffer = new StringBuffer(ors);
        int i = 0;
        while(i < buffer.length()) {
            if(buffer.charAt(i) == '\'' || buffer.charAt(i) == '\\') {
                buffer.insert(i,'\\');
                i+= 2;
            }else {
                i++;
            }
        }
        return buffer.toString();
    }
    /**
     * String去除\
     */
    public static String string2Json(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            switch (c){
                case '\"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }
}
